import React, {useState, useCallback, useRef, useEffect, memo} from 'react';
import {
  SafeAreaView,
  StatusBar,
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Animated,
  Easing,
  InteractionManager,
} from 'react-native';

// 单个动画方块组件
interface AnimatedBoxProps {
  id: number;
  onComplete: (id: number) => void;
}

// 使用 memo 防止父组件重新渲染导致子组件重新渲染
const AnimatedBox = memo(function AnimatedBox({id, onComplete}: AnimatedBoxProps) {
  const translateY = useRef(new Animated.Value(0)).current;
  const onCompleteRef = useRef(onComplete);
  onCompleteRef.current = onComplete;

  useEffect(() => {
    // 使用 InteractionManager 确保在所有交互（包括布局计算）完成后再开始动画
    const handle = InteractionManager.runAfterInteractions(() => {
      Animated.timing(translateY, {
        toValue: 500,
        duration: 3000,
        easing: Easing.out(Easing.cubic), // 开始快，结束慢
        useNativeDriver: false,
      }).start(({finished}) => {
        if (finished) {
          onCompleteRef.current(id);
        }
      });
    });

    return () => handle.cancel();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // 空依赖：只在挂载时执行一次

  return (
    <Animated.View
      style={[
        styles.box,
        {transform: [{translateY}]},
      ]}
    />
  );
});

/**
 * 可变帧率演示Demo
 * 
 * 点击按钮产生一个新的方块从上到下移动，速度逐渐减慢：
 * - 开始阶段：快速移动 → 60fps
 * - 中间阶段：中速移动 → 30fps  
 * - 结束阶段：缓慢移动 → 15fps
 */
function App() {
  const [boxes, setBoxes] = useState<number[]>([]);
  const nextId = useRef(0);

  const spawnBox = useCallback(() => {
    // 延迟 0.5 秒后再创建方块
    setTimeout(() => {
      const id = nextId.current++;
      setBoxes(prev => [...prev, id]);
    }, 500);
  }, []);

  const removeBox = useCallback((id: number) => {
    setBoxes(prev => prev.filter(boxId => boxId !== id));
  }, []);

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />
      <SafeAreaView style={styles.safeArea}>
        <View id="__harmony::ready" />
        
        <Text style={styles.header}>可变帧率演示</Text>
        <Text style={styles.subHeader}>
          点击按钮产生方块，从上到下移动
        </Text>

        {/* 速度阈值说明 */}
        <View style={styles.thresholdInfo}>
          <Text style={styles.thresholdText}>• 速度 {'>'} 120px/s → 60fps</Text>
          <Text style={styles.thresholdText}>• 30-120px/s → 30fps</Text>
          <Text style={styles.thresholdText}>• 速度 {'<'} 30px/s → 15fps</Text>
        </View>

        {/* 动画区域 */}
        <View style={styles.animationArea}>
          {/* 阶段标记 */}
          <View style={[styles.phaseMarker, {top: 0}]}>
            <Text style={styles.markerText}>60fps区</Text>
          </View>
          <View style={[styles.phaseMarker, {top: 166}]}>
            <Text style={styles.markerText}>30fps区</Text>
          </View>
          <View style={[styles.phaseMarker, {top: 333}]}>
            <Text style={styles.markerText}>15fps区</Text>
          </View>
          
          {/* 分隔线 */}
          <View style={[styles.divider, {top: 166}]} />
          <View style={[styles.divider, {top: 333}]} />
          
          {/* 动画方块列表 */}
          {boxes.map(id => (
            <AnimatedBox key={id} id={id} onComplete={removeBox} />
          ))}
        </View>

        {/* 生成按钮 */}
        <TouchableOpacity
          style={styles.button}
          onPress={spawnBox}
        >
          <Text style={styles.buttonText}>
            点击生成方块
          </Text>
        </TouchableOpacity>
      </SafeAreaView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a2e',
  },
  safeArea: {
    flex: 1,
    padding: 16,
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    textAlign: 'center',
    marginBottom: 8,
  },
  subHeader: {
    fontSize: 14,
    color: '#888',
    textAlign: 'center',
    marginBottom: 16,
  },
  thresholdInfo: {
    backgroundColor: '#0f3460',
    borderRadius: 10,
    padding: 12,
    marginBottom: 16,
  },
  thresholdText: {
    fontSize: 12,
    color: '#aaa',
    marginBottom: 4,
  },
  animationArea: {
    height: 500,
    backgroundColor: '#0f0f23',
    borderRadius: 12,
    marginBottom: 16,
    overflow: 'hidden',
    position: 'relative',
    alignItems: 'center',
  },
  phaseMarker: {
    position: 'absolute',
    right: 8,
    paddingHorizontal: 8,
    paddingVertical: 4,
    backgroundColor: 'rgba(255,255,255,0.1)',
    borderRadius: 4,
  },
  markerText: {
    fontSize: 10,
    color: '#666',
  },
  divider: {
    position: 'absolute',
    left: 0,
    right: 0,
    height: 1,
    backgroundColor: 'rgba(255,255,255,0.1)',
  },
  box: {
    position: 'absolute', // 脱离 flex 布局，避免布局重计算影响动画
    top: 0,
    left: '50%',
    marginLeft: -30, // width / 2 的负值，实现水平居中
    width: 60,
    height: 60,
    backgroundColor: '#00ff88',
    borderRadius: 12,
    shadowColor: '#00ff88',
    shadowOffset: {width: 0, height: 0},
    shadowOpacity: 0.5,
    shadowRadius: 15,
  },
  button: {
    backgroundColor: '#00aa55',
    paddingVertical: 14,
    borderRadius: 10,
    alignItems: 'center',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default App;